package me.thinkjet.common;

import me.thinkjet.controller.CommonController;
import me.thinkjet.interceptor.AuthInterceptor;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.RenderingTimeHandler;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.plugin.tablebind.AutoTableBindPlugin;
import com.jfinal.ext.plugin.tablebind.SimpleNameStyles;
import com.jfinal.ext.route.AutoBindRoutes;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.ehcache.EhCachePlugin;

/**
 * API引导式配置
 */
public class Config extends JFinalConfig {

    /**
     * 配置常量
     */
    @Override
    public void configConstant(Constants me) {
	loadPropertyFile("config.properties");
	me.setEncoding("utf-8");
	// me.setViewType(ViewType.JSP);
	me.setDevMode(getPropertyToBoolean("devMode", false));
	me.setBaseViewPath("/WEB-INF/views");
    }

    /**
     * 配置路由
     */
    @Override
    public void configRoute(Routes me) {
	me.add(new AutoBindRoutes());
	me.add("/", CommonController.class);
    }

    /**
     * 配置插件
     */
    @Override
    public void configPlugin(Plugins me) {
	// 配置连接池
	DruidPlugin dp = new DruidPlugin(getProperty("jdbcUrl"),
		getProperty("user"), getProperty("password").trim());
	dp.set(getPropertyToInt("initialSize", 10),
		getPropertyToInt("minIdle", 10),
		getPropertyToInt("maxActive", 100));
	dp.setMaxWait(this.getPropertyToInt("maxWait", 60000));
	dp.setTimeBetweenEvictionRunsMillis(this.getPropertyToInt(
		"timeBetweenEvictionRunsMillis", 60000));
	dp.setMinEvictableIdleTimeMillis(this.getPropertyToInt(
		"minEvictableIdleTimeMillis", 300000));
	// 使用proxyFilters配置Filter，
	dp.addFilter(new StatFilter());// 添加监控
	WallFilter wall = new WallFilter();
	wall.setDbType("mysql");
	dp.addFilter(wall);// 添加注入攻击防御
	me.add(dp);
	AutoTableBindPlugin atbp = new AutoTableBindPlugin(dp,
		SimpleNameStyles.LOWER);
	me.add(atbp);
	me.add(new EhCachePlugin());
    }

    /**
     * 配置全局拦截器
     */
    @Override
    public void configInterceptor(Interceptors me) {
	me.add(new AuthInterceptor());
	me.add(new SessionInViewInterceptor());
    }

    /**
     * 配置处理器
     */
    @Override
    public void configHandler(Handlers me) {
	me.add(new RenderingTimeHandler());
	DruidStatViewHandler dvh = new DruidStatViewHandler("/druid");
	me.add(dvh);

    }

    public static void configAuthentication() {

    }

    public static void main(String[] args) {
	JFinal.start("WebRoot", 81, "/", 5);
    }
}
